<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;

/**
 * 装置管理
 *
 * @icon fa fa-circle-o
 */
class Device extends Backend
{
    
    /**
     * Device模型对象
     * @var \app\admin\model\jdy\Device
     */
    protected $model = null;

    protected $noNeedRight = ['txsz', 'detail', 'getdevHistories', 'chart'];
    protected $isadmin = false;//

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Device;
        $group_ids = $this->auth->getGroupIds();
        if (in_array("2", $group_ids) || in_array("1", $group_ids)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //http://acciot.test/admin/jdy/device/index/ids/21?ref=addtabs
        $room_id = -1;
        $url = $_SERVER['HTTP_REFERER'];
        $anchangname = "";
        $anchangid = 0;
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchangid = $urls[$size - 1];
            $anchang = \app\admin\model\jdy\Anchang::get($anchangid);
            if ($anchang) {
                $room_id = $anchang->room_id;
                $anchangname = $anchang->name;
            }
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where1 = "";
            if ($room_id >= 0) {
                $where1 = " room_id = {$room_id} ";
            } else {
                $roomids = $this->getroomids();
                $where1 = "";
                if (!$this->isadmin) {
                    if (empty($roomids)) {
                        $where1 = " room_id  = 0 ";
                    } else {
                        $where1 = " room_id in (" . $roomids . ") ";
                    }
                }
            }
            $total = $this->model
                ->with(['room','smallcategory'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['room','smallcategory'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                if (empty($anchangname)) {
                    $room_id = $row['room_id'];
                    $anchang = \app\admin\model\jdy\Anchang::where('room_id', $room_id)->find();
                    if ($anchang) {
                        $row['anchangname'] = $anchang->name;
                    }
                } else {
                    $row['anchangname'] = $anchangname;
                }
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $index1url = "/admin/jdy/device/index?ref=addtabs";
        if ($anchangid > 0) {
            $index1url = "/admin/jdy/device/index1/ids/" . $anchangid . "?ref=addtabs";
        }

        $this->view->assign("index1url", $index1url);
        $this->view->assign("anchangname", $anchangname);

        return $this->view->fetch();
    }

    public function index1()
    {
        //http://acciot.test/admin/jdy/device/index1/ids/21?ref=addtabs
        $room_id = -1;
        $url = $_SERVER['HTTP_REFERER'];
        $anchangname = "";
        $anchangid = 0;
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $anchangid = $urls[$size - 1];
            $anchang = \app\admin\model\jdy\Anchang::get($anchangid);
            if ($anchang) {
                $room_id = $anchang->room_id;
                $anchangname = $anchang->name;
            }
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($room_id >= 0) {
                $total = $this->model
                    ->with(['room','smallcategory'])
                    ->where($where)
                    ->where('room_id', $room_id)
                    ->where('smallcategory.id', '>=', '39')
                    ->where('smallcategory.id', '<=', '40')
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['room','smallcategory'])
                    ->where($where)
                    ->where('room_id', $room_id)
                    ->where('smallcategory.id', '>=', '39')
                    ->where('smallcategory.id', '<=', '40')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            } else {
                $total = $this->model
                    ->with(['room','smallcategory'])
                    ->where($where)
                    ->where('smallcategory.id', '>=', '39')
                    ->where('smallcategory.id', '<=', '40')
                    ->order($sort, $order)
                    ->count();

                $list = $this->model
                    ->with(['room','smallcategory'])
                    ->where($where)
                    ->where('smallcategory.id', '>=', '39')
                    ->where('smallcategory.id', '<=', '40')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $row) {


            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $indexurl = "/admin/jdy/device/index?ref=addtabs";
        if ($anchangid > 0) {
            $indexurl = "/admin/jdy/device/index/ids/" . $anchangid . "?ref=addtabs";
        }

        $this->view->assign("indexurl", $indexurl);
        $this->view->assign("anchangname", $anchangname);

        return $this->view->fetch();
    }

    /**
     * 详情 获取Devhistory
     */
    public function detail0()
    {
        $ids = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        }

        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));

        //url获取最新的记录
//        $this->getdevHistories($row['deviceid']);

        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = \app\admin\model\jdy\Devhistory::where($where)
                ->where('sn', $row['deviceid'])
                ->count();

            $list = \app\admin\model\jdy\Devhistory::where($where)
                ->where('sn', $row['deviceid'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            foreach ($list as $row) {

            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }


        $row = $row->toArray();
        $anchang = \app\admin\model\jdy\Anchang::where('room_id', $row['room_id'])->find();
        if ($anchang) {
            $row['anchang'] = $anchang->toArray();
        }

        $this->view->assign("ids", $ids);
        $this->view->assign("row", $row);
//        $this->view->assign("title", "AAA");

        return $this->view->fetch();
    }

    public function chart0()
    {
        $ids = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        }

        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));

        if ($this->request->isPost()) {
            if (empty($_POST['dateInfo'])) {
                $this->error("请选择区域日期");
            }
            $dateInfo = explode(' - ', $_POST['dateInfo']);
            $from = $dateInfo[0];
            $to = $dateInfo[1];
            $from = strtotime($from);
            $to = strtotime($to);

            $list = \app\admin\model\jdy\Devhistory::where('sn', $row['deviceid'])
                ->where('dateInfo', '>', $from)
                ->where('dateInfo', '<', $to)
                ->where('dt', '<>', '--')
                ->where('online', '1')
                ->order('dateInfo', 'ASC')
                ->select();
            $list = collection($list)->toArray();
            $this->success(__('查询成功'), null, $list);
        }

        $from = strtotime("-7 days", time());
        $to = time();
        $list = \app\admin\model\jdy\Devhistory::where('sn', $row['deviceid'])
            ->where('dateInfo', '>', $from)
            ->where('dateInfo', '<', $to)
            ->where('dt', '<>', '--')
            ->where('online', '1')
            ->order('dateInfo', 'ASC')
            ->select();
        $list = collection($list)->toArray();

        $row = $row->toArray();
        $anchang = \app\admin\model\jdy\Anchang::where('room_id', $row['room_id'])->find();
        if ($anchang) {
            $row['anchang'] = $anchang->toArray();
        }

        $this->view->assign("ids", $ids);
        $this->view->assign("from", date("Y-m-d", $from));
        $this->view->assign("to", date("Y-m-d", $to));
        $this->view->assign("list", $list);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //http://acciot.test/admin/jdy/device/getdevHistories?sn=10525301010339
    function getdevHistories($sn)
    {
        if (!$sn) {
            return;
        }

        $linkstatus=  \app\admin\model\jdy\Linkstatus::get(1);
        if ($linkstatus->status == "断线") {
            return;
        }

        $url = "http://s1.yourslink.com:8080/shs-manager/httpApiTWController.do?requestToken&username=enaviapi&password=enavi28960818";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);// 获取头部信息
        curl_setopt($ch, CURLOPT_HEADER, 1);// 返回原生的（Raw）输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// 执行并获取返回结果
        $content = curl_exec($ch);

        $token = "";
        if ($content) {
            list($header, $body) = explode("\r\n\r\n", $content);
            preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
            $cookie = $matches[1];
            $data = $body;


            $ret = json_decode($data, TRUE);
            if ($ret['result'] && $ret['msg_code'] == 0) {
                $token = $ret['message'];
            }
        }

        if (empty($token)) {
            $linkstatus->status = "断线";
            $linkstatus->save();
            return;
        }

        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        $device = \app\admin\model\jdy\Devhistory::where('sn', $sn)->order('dateInfo desc')->limit(1)->find();
        $from = date("Y-m-d", strtotime("-7 days", time()));
        $to = date("Y-m-d", time());
        if ($device) {
            $from = date("Y-m-d", $device['dateInfo']/1000);
        }
        $remark = $sn.','.$from.','.$to;

        $url = "http://s1.yourslink.com:8080/shs-manager/httpApiTWController.do?queryDatas";
        $inputA = array(
            "action" => "devHistories",
            "token" => $token,
            "remark" => $remark,
        );
        $input = json_encode($inputA);
        $url .= "&requestInfoJson=" . $input;
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);// 执行并获取返回结果
        $data = curl_exec($ch);
        curl_close($ch);

        $ret = json_decode($data, TRUE);
        if ($ret['result'] && $ret['msg_code'] == 0) {
            $message = $ret['message'];
            $data = json_decode($message, TRUE);
            $total = $data["total"];
            $devHistorieslist = $data["rows"];
            $size = count($devHistorieslist);

            foreach ($devHistorieslist as $row) {
                $device = \app\admin\model\jdy\Devhistory::where('devhistoryid', $row['id'])->find();
                if (!$device) {
                    $device = new \app\admin\model\jdy\Devhistory();
                }
                $device->devhistoryid = $row['id'];
                $device->sn = $row['sn'];
                $device->t = $row['time'];
                $device->d = $row['date'];
                $device->online = $row['online'];
                $device->state = $row['state'];
                $device->dt = $row['durationTime'];
                $device->dateInfo = $row['dateInfo'];
                $device->save();
            }

//            echo $total.'<br>';
        }

//        echo $sn . '<br>';

    }

    /**
     * 详情 获取devicelog
     */
    public function detail()
    {
        $ids = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        }

        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));

        $deviceB = $this->getGAB($row);
        $glsb = "";
        if (!empty($deviceB)) {
            $glsb = $deviceB->name;
        }

        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            if ($deviceB) {
                $where1 = " (device_id = " . $row['id'] . " or device_id = " . $deviceB['id'] . ")";
            } else {
                $where1 = " device_id = " . $row['id'];
            }
            $total = \app\admin\model\jdy\Devicelog::where($where)
                ->where($where1)
                ->count();

            $list = \app\admin\model\jdy\Devicelog::where($where)
                ->where($where1)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            $pretime = time();
            foreach ($list as &$row0) {
                $row0['name'] = $row['name'];
                if ($deviceB && $row0['device_id'] != $row['id']) {
                    $row0['name'] = $deviceB['name'];
                }

                $all = $pretime - $row0['starttime']; //秒
                $h = intval($all / 3600);
                $m = intval(($all - $h * 3600) / 60);
                $s = intval($all % 60);
                if ($m < 10) {
                    $m = '0'.$m;
                }
                if ($s < 10) {
                    $s = '0'.$s;
                }
                $row['dt'] = $h . ":" . $m . ':' . $s; //秒
                $pretime = $row0['starttime'];
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $row = $row->toArray();
        $anchang = \app\admin\model\jdy\Anchang::where('room_id', $row['room_id'])->find();
        if ($anchang) {
            $row['anchang'] = $anchang->toArray();
        }

        $this->view->assign("ids", $ids);
        $this->view->assign("row", $row);
        $this->view->assign("glsb", $glsb);

        return $this->view->fetch();
    }

    //获取对应的G裝置代號
    function getGAB($row)
    {
        if (empty($row)) {
            return null;
        }

        $name = $row->name;
        if (empty($name)) {
            return null;
        }

        $len = strlen($name);
        if ($len < 3) {
            return null;
        }

        $G = substr($name, -1, 1);

        if ($G == "G") {
            $A = substr($name, -2, 1);
            $B = "B"; //泵的编号 A-B泵对应
            if ($A == "B") {
                $B = "A";
            }
            $pre = substr($name, 0, $len - 2);
            $nameB = $pre . $B . "G";

            $deviceB = \app\admin\model\jdy\Device::where("room_id", $row->room_id)->where("name", $nameB)->find();
            return $deviceB;
        }
        return null;
    }

    public function chart()
    {
        $ids = 0;
        $url = $_SERVER['HTTP_REFERER'];
        if (false !== strpos($url, '/ids/')) {
            $urls = explode('?', $url);
            $url = $urls[0];
            $urls = explode('/', $url);
            $size = count($urls);
            $ids = $urls[$size - 1];
        }

        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));

        $deviceB = $this->getGAB($row);
        $glsb = "";
        if (!empty($deviceB)) {
            $glsb = $deviceB->name;
        }

        $list2 = [];

        if ($this->request->isPost()) {
            $from = strtotime("-7 days", time());
            $from = strtotime(date("Y-m-d", $from));
            $to = time();

            if (!empty($_POST['dateInfo'])) {
                $dateInfo = explode(' - ', $_POST['dateInfo']);
                $from = $dateInfo[0];
                $to = $dateInfo[1];
                $from = strtotime($from);
                $to = strtotime($to);
            }

            if ($deviceB) {
                $where1 = " (device_id = " . $row['id'] . " or device_id = " . $deviceB['id'] . ")";
            } else {
                $where1 = " device_id = " . $row['id'];
            }
            $list = \app\admin\model\jdy\Devicelog::where($where1)
                ->where('starttime', '>', $from)
                ->where('starttime', '<', $to)
                ->order('id', 'DESC')
                ->select();

            $list = collection($list)->toArray();
            $weekarray = array("日", "一", "二", "三", "四", "五", "六");
            $endtime = time();

            foreach ($list as &$row1) {
                $all = $endtime - $row1['starttime']; //秒
                $h = intval($all / 3600);
                $m = intval(($all - $h * 3600) / 60);
                $s = intval($all % 60);
                if ($m < 10) {
                    $m = '0'.$m;
                }
                if ($s < 10) {
                    $s = '0'.$s;
                }
                $row1['dt'] = $h . ":" . $m . ':' . $s; //秒
                $row1['all'] = $all;
                $row1['info'] = date("Y-m-d H:i:s", $row1['starttime'])." ~ ".date("Y-m-d H:i:s", $endtime);

                if ($row1['online'] == 1) {
                    $starttime0 = $row1['starttime'];
                    $list3 = [];
                    while (1) {
                        $rowX = [];
                        $rowX['dt'] = $row1['dt'];

                        $nexttime = strtotime("+1 day", strtotime(date("Y-m-d", $starttime0))) - 1; //次日
                        $finish = false;
                        if ($nexttime > $endtime) {
                            $nexttime = $endtime;
                            $finish = true;
                        }

                        $weekinfo = "星期" . $weekarray[date("w", $starttime0)];
                        $rowX['d'] = date("Y-m-d", $starttime0) . "\n" . $weekinfo;
                        $rowX['start0'] = strtotime(date("Y-m-d", $starttime0));//当天0点
                        $rowX['start'] = $starttime0;
                        $rowX['end'] = $nexttime;
                        $rowX['x0'] = ($rowX['start'] - $rowX['start0'] + 57600) * 1000;
                        $rowX['x1'] = ($rowX['end'] - $rowX['start0'] + 57600) * 1000;
                        $rowX['info'] = $row1['info'];
                        $rowX['id'] = $row1['id'];
                        $rowX['device_id'] = $row1['device_id'];

                        $list3[] = $rowX;

                        $starttime0 = $nexttime + 1;
                        if ($starttime0 > $to) {
                            $finish = true;
                        }

                        if ($finish) {
                            break;
                        }
                    }

                    $list3 = array_reverse($list3);
                    foreach ($list3 as $row3) {
                        $list2[] = $row3;
                    }
                }

                $endtime = $row1['starttime'] - 1;
            }
            $list2 = array_reverse($list2);
//            arsort($list2);
            $this->success(__('查询成功'), null, $list2);
        }

        $row = $row->toArray();
        $row['glsb'] = $glsb;
        $anchang = \app\admin\model\jdy\Anchang::where('room_id', $row['room_id'])->find();
        if ($anchang) {
            $row['anchang'] = $anchang->toArray();
        }

        $this->view->assign("ids", $ids);
        $this->view->assign("list", $list2);
        $this->view->assign("row", $row);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function txsz($ids = null)
    {
        $model = new \app\admin\model\jdy\Devicealarmset;
        $this->view->assign("warningTypeList", $model->getWarningTypeList());
        $this->view->assign("warningStatusList", $model->getWarningStatusList());
        $this->view->assign("warningSwitchList", $model->getWarningSwitchList());
        $this->view->assign("warning1StatusList", $model->getWarning1StatusList());
        $this->view->assign("warningWayList", $model->getWarningWayList());
        $this->view->assign("d0StandardSwitchList", $model->getD0StandardSwitchList());
        $this->view->assign("d1StandardSwitchList", $model->getD1StandardSwitchList());
        $this->view->assign("d2StandardSwitchList", $model->getD2StandardSwitchList());
        $this->view->assign("d3StandardSwitchList", $model->getD3StandardSwitchList());
        $this->view->assign("d4StandardSwitchList", $model->getD4StandardSwitchList());
        $this->view->assign("d5StandardSwitchList", $model->getD5StandardSwitchList());
        $this->view->assign("d6StandardSwitchList", $model->getD6StandardSwitchList());

        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $deviceset = \app\admin\model\jdy\Devicealarmset::where('device_id', $row['id'])->find();
        if (!$deviceset) {
            //应该进不来，$jdyalarm->addsetfordevice()已处理
            $deviceset = new \app\admin\model\jdy\Devicealarmset();
            $deviceset->device_id = $row['id'];
            $deviceset = $this->getRAB($row, $deviceset);
            $deviceset->save();
            $deviceset = \app\admin\model\jdy\Devicealarmset::get($deviceset->id);
        } else {
            if ($deviceset['device1_id'] < 1) {
                $deviceset = $this->getRAB($row, $deviceset);
                $deviceset->save();
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    $result = $deviceset->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $smallcategory_id = intval($row['smallcategory_id']);
        $deviceset = $deviceset->toArray();
        $deviceset['devicename'] = $row['name'];
        $deviceset['deviceselfname'] = $row['selfname'];

        $deviceset['smallcategoryname'] = "";
        $smallcategory = \app\admin\model\jdy\Smallcategory::get($smallcategory_id);
        if ($smallcategory) {
            $deviceset['smallcategoryname'] = $smallcategory->name;
        }

        $deviceset['device1name'] = "";
        if ($deviceset['device1_id'] > 0) {
            $device1 = \app\admin\model\jdy\Device::get($deviceset['device1_id']);
            if ($device1) {
                $deviceset['device1name'] = $device1->name;
            }
        }

        $deviceset['device2name'] = "";
        if ($deviceset['device2_id'] > 0) {
            $device2 = \app\admin\model\jdy\Device::get($deviceset['device2_id']);
            if ($device2) {
                $deviceset['device2name'] = $device2->name;
            }
        }

        $this->view->assign("row", $deviceset);

        $type0array = [0, 36, 41, 42, 44, 45, 46, 47];
        if (in_array($smallcategory_id, $type0array)) {
            //一般設備
            return $this->view->fetch('ybsb');
        } else if ($smallcategory_id == 39) {
            //一般設備G
            return $this->view->fetch('ybg');
        } else if ($smallcategory_id == 40) {
            //一般設備R
            return $this->view->fetch('ybr');
        }

        return $this->view->fetch();

    }

    //获取对应的R裝置代號
    //$row--device     $deviceset--set
    //清BR      清BAG+清BBG
    function getRAB($row, $deviceset)
    {
        if (empty($row)) {
            return $deviceset;
        }

        $name = $row->name;
        if (empty($name)) {
            return $deviceset;
        }

        $len = strlen($name);
        if ($len < 3) {
            return $deviceset;
        }

        $R = substr($name, -1, 1);

        if ($R == "R") {
            $pre = substr($name, 0, $len - 1);
            $nameA = $pre . "AG";
            $nameB = $pre . "BG";
            $deviceA = \app\admin\model\jdy\Device::where("room_id", $row->room_id)->where("name", $nameA)->find();
            $deviceB = \app\admin\model\jdy\Device::where("room_id", $row->room_id)->where("name", $nameB)->find();
            if ($deviceA) {
                $deviceset['device1_id'] = $deviceA->id;
            }
            if ($deviceB) {
                $deviceset['device2_id'] = $deviceB->id;
            }
        } else if ($R == "G") {
            // G装置
            $deviceB = $this->getGAB($row);
            if ($deviceB) {
                $deviceset['device1_id'] = $deviceB->id;
            }
        }
        return $deviceset;
    }

    public function getanchanglist()
    {
        $anchangidlist = json_decode($this->auth->anchangids, TRUE);
        $xianshi = [];
        $xianshi[] = $this->auth->xianshi1;
        $xianshi[] = $this->auth->xianshi2;
        $xianshi[] = $this->auth->xianshi3;
        $xianshi[] = $this->auth->xianshi4;
        $xianshi[] = $this->auth->xianshi5;

        $xzq = [];
        $xzq[] = $this->auth->xzq1;
        $xzq[] = $this->auth->xzq2;
        $xzq[] = $this->auth->xzq3;
        $xzq[] = $this->auth->xzq4;
        $xzq[] = $this->auth->xzq5;

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $list = [];
        if (!empty($whereA)) {
            $list = \app\admin\model\jdy\Anchang::where($whereA)->select();
        }

        return $list;
    }

    public function getanchangids() {
        $anchangidlist = $this->getanchanglist();
        $anchangids = "";
        foreach ($anchangidlist as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }
        return $anchangids;
    }

    public function getroomids()
    {
        $anchangidlist = $this->getanchanglist();
        $roomids = "";

        foreach ($anchangidlist as $row) {
            $anchang = \app\admin\model\jdy\Anchang::get($row['id']);

            if (empty($roomids)) {
                $roomids = $anchang['room_id'];
            } else {
                $roomids .= ',' . $anchang['room_id'];
            }
        }
        return $roomids;
    }

}
